<template>
  <div class="app-container remain-wrap">
    <el-form :inline="true" ref="ruleForm" :model="form" class="demo-form-inline">

      <el-form-item label="时间区间" prop="time">
        <el-date-picker v-model="form.time" type="daterange" align="right" unlink-panels range-separator="至"
          start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd" :picker-options="pickerDayStep">
        </el-date-picker>
      </el-form-item>
      <el-form-item prop="rateType">
        <div style="">
          <el-radio-group v-model="rateType" size="small" @change="changeRadio">
            <el-radio label="loginRate" border>登陆用户留存率</el-radio>
            <!--<el-radio label="activeRate" border>活跃用户留存率</el-radio>-->
          </el-radio-group>
        </div>
      </el-form-item>
      <el-form-item label="代理账号：" prop="proxy">
        <el-input v-model="form.proxy" @keyup.enter.native="getGridData"></el-input>
      </el-form-item>
      <!--<el-form-item label="域名地址：">-->
      <!--<el-select v-model="form.domain" style="width: 120px;">-->
      <!--<el-option-->
      <!--v-for="item in domainList"-->
      <!--:value="item.value"-->
      <!--:label="item.title"-->
      <!--:key="item.value"-->
      <!--&gt;</el-option>-->
      <!--</el-select>-->
      <!--</el-form-item>-->
      <el-form-item>
        <div class="filter-right">
          <el-button @click="changePeriod('day')" type="text" :class="{active:period=='day'}">日</el-button>
          <el-button @click="changePeriod('week')" type="text" :class="{active:period=='week'}">周</el-button>
          <el-button @click="changePeriod('month')" type="text" :class="{active:period=='month'}">月</el-button>
          &nbsp;&nbsp;|&nbsp;&nbsp;
          <el-button @click="changeFormat('num')" type="text" :class="{active:format=='num'}">留存用户数</el-button>
          &nbsp;&nbsp;|&nbsp;&nbsp;
          <el-button @click="changeFormat('rate')" type="text" :class="{active:format=='rate'}">留存率</el-button>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button class="filter-item" type="primary" icon="el-icon-search" @click="getGridData()" ref="$_btn">搜索
        </el-button>
        <el-button @click="reset">重置</el-button>
      </el-form-item>
      <!--<input type="hidden" name="period" :value="form.period">-->
      <!--<input type="hidden" name="format" :value="form.format">-->
    </el-form>

    <el-table :data="tableData" v-loading="loading" element-loading-text="给我一点时间" border fit height="450"
      highlight-current-row style="width: 100%">
      <el-table-column label="时间" fixed align="center" width="160px">
        <template slot-scope="{row}">
          {{row.date}}
        </template>
      </el-table-column>
      <el-table-column label="新增用户" align="center">
        <template slot-scope="{row}">
          {{row.num[0]}}
        </template>
      </el-table-column>
      <el-table-column align="center" v-for="(col,index) in colList[period]" :key="index" :label="col">
        <template slot-scope="{row}">
          <span v-if="format === 'num'">{{row.num[index+1]}}</span>
          <span
            v-else-if="format === 'rate' && (row.num[index+1] === 0 || row.num[index+1] === null)">{{row.num[index+1] === null ? '' : 0}}</span>
          <span
            v-else-if="format === 'rate' && row.num[index+1] !=0 && row.num[index+1] != null && row.num[index+1]">{{(row.num[index+1] / row.num[0])*100 | currency}}%</span>
        </template>
      </el-table-column>
    </el-table>
    <el-card class="box-card">
      <div slot="header" class="clearfix bg-pure-dark">
        <el-row>
          <el-col :span="6" class="">
            <div class="">留存率图表</div>


          </el-col>
          <el-col :span="18" class="">
            <div class="filter-right">
              <el-button @click="changeRange(1)" type="text" :class="{active:range==1}">过去1天</el-button>
              <el-button @click="changeRange(3)" type="text" :class="{active:range==3}">过去3天</el-button>
              <el-button @click="changeRange(7)" type="text" :class="{active:range==7}">过去7天</el-button>
              <el-button @click="changeRange(9)" type="text" :class="{active:range==9}">过去30天</el-button>
            </div>
          </el-col>
        </el-row>
      </div>
      <div class="height-300" ref="profitChart">
        <category-chart :x-data="currentXData" :y-data="currentYData"></category-chart>
      </div>
    </el-card>

  </div>
</template>

<script>
  import {
    form,
    grid,
    dialog,
    pickerOption
  } from '@/build';
  import categoryChart from '../components/categoryChart'
  import {
    retentionActiveUserApi as activeListApi,
    retentionLoginUserApi as loginListApi,
  } from '@/services/api/operational';

  export default {
    name: 'remain-rate',

    mixins: [form, grid, dialog, pickerOption],

    components: {
      // SubList
      categoryChart,
    },

    data() {
      // let times = _.toPeriod({
      //   start: [-1, 'days'],
      //   end: [0, 'days'],
      //   format: 'YYYY-MM-DD'
      // });
      // 本月时间本月1号至当前时间
      // const monthTime = [moment().startOf('month').format('YYYY-MM-DD'), moment().format('YYYY-MM-DD')]
      const monthTime = [moment().add(-8, 'days').format('YYYY-MM-DD'), moment().add(-2, 'days').format('YYYY-MM-DD')]

      return {
        period: 'day',
        range: 1,
        format: 'rate',
        colList: {
          day: [
            '1天后',
            '2天后',
            '3天后',
            '4天后',
            '5天后',
            '6天后',
            '7天后',
            '14天后',
            '30天后',
          ],
          week: [
            '1周后',
            '2周后',
            '3周后',
            '4周后',
            '5周后',
            '6周后',
            '7周后',
            '8周后',
            '9周后',
          ],
          month: [
            '1月后',
            '2月后',
            '3月后',
            '4月后',
            '5月后',
            '6月后',
            '7月后',
            '8月后',
            '9月后',
          ],
        },
        rateType: 'loginRate', // activeRate
        domainList: [{
            value: '1',
            title: 'www.google.com',
          },
          {
            value: '2',
            title: 'www.baidu.com',
          }
        ],
        tableData: [],
        form: {
          time: monthTime,
          proxy: undefined,
          domain: undefined,
          type: 'day',
          // format: 'rate',
        },
        filters: {
          stime: moment(monthTime[0]).valueOf(),
          etime: moment(monthTime[1]).valueOf() + 86399999,
        },
      }
    },
    computed: {
      ...mapGetters([]),
      ...mapState({
        report: state => state.report,
      }),
      periodName() {
        let periodName = '天';
        switch (this.period) {
          case 'day':
            periodName = '天';
            break;
          case 'week':
            periodName = '周';
            break;
          case 'month':
            periodName = '月';
            break;
          default:
            periodName = '';
        }
        return periodName;
      },
      //实时当前图表数据
      currentDate() {
        let array = []
        this.tableData.map((item, index) => {
          array.push({
            x: item.date,
            y: this.format === 'num' ? item.num[this.range] : item.num[this.range] / item.num[0]
          })
        })
        return _.sortBy(array, (item) => {
          return item.x;
        })
      },
      currentXData() {
        return _.map(this.currentDate, (item) => {
          return item.x;
        })
      },
      currentYData() {
        return _.map(this.currentDate, (item) => {
          return item.y;
        })
      },
    },

    mounted() {
      this.bindGet(activeListApi, 'tableData', {
        action: 'getActiveGrid',
        sendingData: 'filters',
      });
      this.bindGet(loginListApi, 'tableData', {
        action: 'getLoginGrid',
        sendingData: 'filters',
      });
      this.getGridData();
    },
    methods: {
      reset() {
        this.resetForm('ruleForm');
        this.changePeriod('day');
        this.changeFormat('rate');
        this.rateType = 'loginRate'
        this.changeRadio('loginRate');
      },
      changeRadio(val) {
        this.getGridData()
      },
      getGridData() {
        const {
          time,
          proxy,
          domain,
          type
        } = this.form;
        let stime = undefined,
          etime = undefined;
        if (!_.isUndefined(time) && _.isArray(time)) {
          if (this.form.type == 'day') {
            stime = moment(time[0]).valueOf();
            etime = moment(time[1]).valueOf() + 86399999;
          } else if (this.form.type == 'week') {
            stime = moment(time[1]).add(-8, 'week').valueOf();
            etime = moment(time[1]).valueOf() + 86399999;
          } else {
            stime = moment(time[1]).add(-8, 'month').valueOf();
            etime = moment(time[1]).valueOf() + 86399999;
          }
        }
        // if (!_.isUndefined(time) && _.isArray(time)) {
        //   debugger
        //   stime = moment(time[0]).valueOf();
        //   etime = moment(time[1]).valueOf() +  86399999;
        // }
        this.filters = {
          stime,
          etime,
          proxy,
          domain,
          type,
          project: consts.PLATFROM_PREFIX
        }
        if (this.rateType == 'loginRate') {
          this.doGet({
            action: 'getLoginGrid'
          });
        } else if (this.rateType == 'activeRate') {
          this.doGet({
            action: 'getActiveGrid'
          });
        }
      },
      changePeriod(period) {
        this.form.type = period; //是否作为参数传输？
        this.period = period;
        switch (this.period) {
          case 'day':
            this.form.time = [moment().add(-8, 'days').format('YYYY-MM-DD'), moment().add(-2, 'days').format(
              'YYYY-MM-DD')]
            break;
          case 'week':
            this.form.time = [moment().add(-8, 'week').format('YYYY-MM-DD'), moment().add(-2, 'days').format(
              'YYYY-MM-DD')]
            break;
          case 'month':
            this.form.time = [moment().add(-8, 'month').format('YYYY-MM-DD'), moment().add(-2, 'days').format(
              'YYYY-MM-DD')]
            break;
        }
        this.getGridData()
      },
      changeFormat(formate) {
        this.format = formate;
        // 切换数据的类型，数字和比例
      },
      changeRange(range) {

        this.range = range;
      },
      getClassByRate(rate) {
        let className = 'level';
        let round = Math.round(rate * 10);
        // switch(round){
        //   case 1: className='level'+round;break;
        // }
        return className + round;
      }
    },
  }

</script>
<style lang="scss">
  .remain-wrap {
    .el-button--text {
      color: #909399;

      &.active {
        color: #409EFF
      }
    }
  }

</style>
